package com.cykj.web.controller.posbiz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cykj.common.annotation.Log;
import com.cykj.common.core.controller.BaseController;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.core.page.TableDataInfo;
import com.cykj.common.enums.BusinessType;
import com.cykj.common.utils.SecurityUtils;
import com.cykj.common.utils.StringUtils;
import com.cykj.common.utils.poi.ExcelUtil;
import com.cykj.pos.domain.*;
import com.cykj.pos.domain.dto.*;
import com.cykj.pos.domain.posone.PosOneMerchantInfo;
import com.cykj.pos.domain.vo.BizGdbArea;
import com.cykj.pos.domain.vo.BizTransactionAmountEntityVO;
import com.cykj.pos.mapper.BizMerchantInfoMapper;
import com.cykj.pos.mapper.BizPosMachineMapper;
import com.cykj.pos.profit.dto.MerchantDTO;
import com.cykj.pos.service.*;
import com.cykj.pos.util.HttpUtil;
import com.cykj.pos.util.PublicUtil;
import com.cykj.system.mapper.SysDictDataMapper;
import com.github.pagehelper.util.StringUtil;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.*;

/**
 * 商户基本信息Controller
 *
 * @author xuxiaolong
 * @date 2022-08-09
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/pos/merchantInfo")
public class BizMerchantInfoController extends BaseController {

    private final IBizMerchantInfoService iBizMerchantInfoService;
    private final IBizMerchantService bizMerchantService;
    private final IBizMerchantEntryService iBizMerchantEntryService;
    @Autowired
    BizPosMachineMapper posMachineMapper;
    private final IBizPosMachineService posMachineService;

    private final BizMerchantInfoMapper bizMerchantInfoMapper;

    private final com.cykj.pos.domain.PosPCommonParamConfig PosPCommonParamConfig;

    private final IBizMerchTransactionsService iBizMerchTransactionsService;
    private final SysDictDataMapper sysDictDataMapper;
    //获取审核状态
    // private String urlGetMerchantStatus = "http://82.156.56.242:6060/noAuth/getMerchantStatus?";

    private final IAllocationRelationService iAllocationRelationService;
    /**
     * 新增商户基本信息
     *
     * @param bizMerchantInfo
     * @return
     */
    @PostMapping("/add/merchant/info")
    public AjaxResult addMerchantsInfo(@RequestBody BizMerchantInfo bizMerchantInfo) {
        System.out.println("商户报件："+bizMerchantInfo);
        AjaxResult ajaxResult = AjaxResult.success();
        try {
            String bankCode=this.getBankCode(bizMerchantInfo.getBankCardAccount());
            if(bankCode.equals("0")){
                ajaxResult.put("data", AjaxResult.error("银行卡号不符合，请重试。"));
                System.out.println("银行卡号不符合，请重试。");
                return ajaxResult;
            }
            bizMerchantInfo.setBankCode(bankCode);
        }catch (Exception e){
            e.printStackTrace();
            ajaxResult.put("data", AjaxResult.error("银行卡号不符合，请重试。"));
            System.out.println("银行卡号不符合，请重试。");
            return ajaxResult;
        }
        try {
            String unionpayCode=this.getUnionpayCode(bizMerchantInfo);
            if(unionpayCode.equals("0")){
                ajaxResult.put("data", AjaxResult.error("不支持改地区银行，请更换结算卡"));
                System.out.println("不支持改地区银行，请更换结算卡");
                return ajaxResult;
            }
            if(unionpayCode.indexOf(",")>0){
                String [] ucs=unionpayCode.split(",");
                bizMerchantInfo.setUnionpayCode(ucs[0]);
                bizMerchantInfo.setBankSite(ucs[1]);
            }else{
                bizMerchantInfo.setUnionpayCode(unionpayCode);
            }

        }catch (Exception e){
            e.printStackTrace();
            ajaxResult.put("data", AjaxResult.error("联行号获取失败，请重试。"));
            System.out.println("联行号获取失败，请重试。");
            return ajaxResult;
        }
        if(null!=bizMerchantInfo.getContactPhoneNo()){
            bizMerchantInfo.setContactPhoneNo(bizMerchantInfo.getContactPhoneNo().replace(" ",""));
            bizMerchantInfo.setPhone(bizMerchantInfo.getPhone().replace(" ",""));
            bizMerchantInfo.setBankCardPhone(bizMerchantInfo.getBankCardPhone().replace(" ",""));
            bizMerchantInfo.setClientServicePhoneNo(bizMerchantInfo.getClientServicePhoneNo().replace(" ",""));
            if(bizMerchantInfo.getContactPhoneNo().length()!=11){
                ajaxResult.put("data", AjaxResult.error("手机号长度不正确，请重新输入手机号"));
                System.out.println("手机号长度不正确，请重新输入手机号");
                return ajaxResult;
            }
        }else{
            ajaxResult.put("data", AjaxResult.error("手机号不能为空，请填写手机号"));
            System.out.println("手机号不能为空，请填写手机号");
            return ajaxResult;
        }
        if(null!=bizMerchantInfo.getCertificateNo()){
            bizMerchantInfo.setCertificateNo(bizMerchantInfo.getCertificateNo().replace(" ",""));
        }
        if(null!=bizMerchantInfo.getBankCardAccount()){
            bizMerchantInfo.setBankCardAccount(bizMerchantInfo.getBankCardAccount().replace(" ",""));
        }
        if(null==bizMerchantInfo.getActiveLatitude()||"".equals(bizMerchantInfo.getActiveLatitude())){
            ajaxResult.put("data", AjaxResult.error("经纬度不能为空，请检查手机定位是否开启！"));
            System.out.println("经纬度不能为空，请检查手机定位是否开启！");
            return ajaxResult;
        }
        if(null==bizMerchantInfo.getActiveLongitude()||"".equals(bizMerchantInfo.getActiveLongitude())){
            ajaxResult.put("data", AjaxResult.error("经纬度不能为空，请检查手机定位是否开启！"));
            System.out.println("经纬度不能为空，请检查手机定位是否开启！");
            return ajaxResult;
        }
//        if(null==bizMerchantInfo.getRegisterLatitude()||"".equals(bizMerchantInfo.getRegisterLatitude())){
//            ajaxResult.put("data", AjaxResult.error("经纬度不能为空，请检查手机定位是否开启！"));
//            return ajaxResult;
//        }
//        if(null==bizMerchantInfo.getRegisterLongitude()||"".equals(bizMerchantInfo.getRegisterLongitude())){
//            ajaxResult.put("data", AjaxResult.error("经纬度不能为空，请检查手机定位是否开启！"));
//            return ajaxResult;
//        }
        bizMerchantInfo.setPosCode(bizMerchantInfo.getPosCode().replace(" ",""));
        bizMerchantInfo.setPosCode(bizMerchantInfo.getPosCode().toUpperCase());
        JSONObject result = iBizMerchantInfoService.addMerchantsInfo(bizMerchantInfo);
        ajaxResult.put("data", result);
        return ajaxResult;
    }

    /**
     * 修改商户基本信息
     *
     * @param bizMerchantInfo
     * @return
     */
    @PostMapping("/update/merchant/info")
    public AjaxResult updateMerchantsInfo(@RequestBody BizMerchantInfo bizMerchantInfo) {
//        AjaxResult ajaxResult = AjaxResult.success();
//        JSONObject result = iBizMerchantInfoService.updateMerchantsInfo(bizMerchantInfo);
//        ajaxResult.put("data", result);
        AjaxResult ajaxResult = AjaxResult.error();
        ajaxResult.put("msg","请更新APP,再修改结算卡");
        return ajaxResult;
    }


    /**
     * 全件修改基本信息
     *
     * @param bizMerchantInfo
     * @return
     */
    @PostMapping("/updateAll/merchant/info")
    public AjaxResult updateAllMerchantsInfo(@RequestBody BizMerchantInfo bizMerchantInfo) {
        AjaxResult ajaxResult = AjaxResult.success();
        System.out.println("全件修改："+bizMerchantInfo);
        try {
            String bankCode=this.getBankCode(bizMerchantInfo.getBankCardAccount());
            if(bankCode.equals("0")){
                ajaxResult.put("data", AjaxResult.error("银行卡号不符合，请重试。"));
                return ajaxResult;
            }
            bizMerchantInfo.setBankCode(bankCode);
        }catch (Exception e){
            e.printStackTrace();
            ajaxResult.put("data", AjaxResult.error("银行卡号不符合，请重试。"));
            return ajaxResult;
        }
        try {
            if(bizMerchantInfo.getPosCode() == null || "".equals(bizMerchantInfo.getPosCode())){
                ajaxResult.put("data", AjaxResult.error("设备号为空, 请核实再提交"));
            }
            BizPosMachine bizPosMachine = posMachineService.getPosMachineBySnCode(bizMerchantInfo.getPosCode());
            if(bizPosMachine != null && "2".equals(bizPosMachine.getChannel())){
                String provinceName = bizMerchantInfo.getProvinceName();
                if(provinceName == null || "".equals(provinceName)){
                    ajaxResult.put("data", AjaxResult.error("未选择省"));
                }
                String cityName = bizMerchantInfo.getCityName();
                if(cityName == null || "".equals(cityName)){
                    ajaxResult.put("data", AjaxResult.error("未选择市"));
                }
                String areaName = bizMerchantInfo.getAreaName();
                if(areaName == null || "".equals(areaName)){
                    ajaxResult.put("data", AjaxResult.error("未选择区县"));
                }
                String bankName = getBankName(bizMerchantInfo.getBankCardAccount());
                if(bankName == "FAILURE"){
                    ajaxResult.put("data", AjaxResult.error("银行卡号不符合，请重试。"));
                }
                logger.info(bizMerchantInfo.getBankCardAccount(),"*-*-*-*provinceName:"+provinceName,"cityName:"+cityName,"areaName"+areaName);
                //详细查区县
                BizKdbBank bizKdbBank = bizMerchantInfoMapper.getKdbBank(provinceName,cityName,areaName,bankName);
                if(bizKdbBank != null){
                    bizMerchantInfo.setUnionpayCode(bizKdbBank.getCode());
                    bizMerchantInfo.setBankSite(bizKdbBank.getName());
                }else{// 查市
                    bizKdbBank = bizMerchantInfoMapper.getKdbBankEndCity(provinceName,cityName,bankName);
                    if(bizKdbBank != null){
                        bizMerchantInfo.setUnionpayCode(bizKdbBank.getCode());
                        bizMerchantInfo.setBankSite(bizKdbBank.getName());
                    }else{// 查省
                        bizKdbBank = bizMerchantInfoMapper.getKdbBankEndProvince(provinceName,bankName);
                        if(bizKdbBank != null){
                            bizMerchantInfo.setUnionpayCode(bizKdbBank.getCode());
                            bizMerchantInfo.setBankSite(bizKdbBank.getName());
                        }else{
                            ajaxResult.put("data", AjaxResult.error("不支持改地区银行，请更换结算卡"));
                        }
                    }
                }
                logger.info(bizMerchantInfo.getUnionpayCode(),bizMerchantInfo.getBankSite());
            }else{
                String unionpayCode=this.getUnionpayCode(bizMerchantInfo);
                if(unionpayCode.equals("0")){
                    ajaxResult.put("data", AjaxResult.error("不支持改地区银行，请更换结算卡"));
                    return ajaxResult;
                }
                if(unionpayCode.indexOf(",")>0){
                    String [] ucs=unionpayCode.split(",");
                    bizMerchantInfo.setUnionpayCode(ucs[0]);
                    bizMerchantInfo.setBankSite(ucs[1]);
                }else{
                    bizMerchantInfo.setUnionpayCode(unionpayCode);
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            ajaxResult.put("data", AjaxResult.error("联行号获取失败，请重试。"));
            return ajaxResult;
        }
        JSONObject result = iBizMerchantInfoService.updateAllMerchantsInfo(bizMerchantInfo);
        ajaxResult.put("data", result);
        return ajaxResult;
    }

    ///////批量修改费率
    @PostMapping("/plUpdateFee")
    public AjaxResult plUpdateFee(){
        return iBizMerchantInfoService.plUpdateFee();
    }
    /**
     * 修改费率
     * @return
     */
    @PostMapping("/updateMerchantFee")
    public AjaxResult updateMerchantFee(@RequestBody BizMerchantInfo bizMerchantInfo) {
        return iBizMerchantInfoService.updateMerchantFee(bizMerchantInfo);
    }

    @PostMapping("/updateInfoFeeTenPlusThousandsOne")
    public AjaxResult updateInfoFeePlusTenThousandsOne(){
        return iBizMerchantInfoService.updateInfoFeePlusTenThousandsOne();
    }

    /**
     * 修改结算卡
     * @param bizMerchantInfo
     * @return
     */
    @PostMapping("/updateSettleAccount")
    public AjaxResult updateSettleAccount(@RequestBody BizMerchantInfo bizMerchantInfo) {
        AjaxResult ajaxResult = AjaxResult.success();
        JSONObject result = iBizMerchantInfoService.updateSettleAccount(bizMerchantInfo);
        ajaxResult.put("data", result);
        return ajaxResult;

    }

    /**
     * 接收更新商户状态
     * @param bizMerchantInfo
     * @return
     */
    @PostMapping("/updateSettleAccountStatus")
    public AjaxResult updateSettleAccountStatus(@RequestBody BizMerchantInfo bizMerchantInfo) {
        System.out.println(bizMerchantInfo);
        iBizMerchantInfoService.updateSettleAccountStatusByMerchantCode(bizMerchantInfo);
        return AjaxResult.success();
    }


    @ApiOperation("回显商户信息")
    @PostMapping("/getMerchantInfo")
    public AjaxResult getMerchantInfo(@RequestBody BizMerchantInfo bizMerchantInfo) {
        BizMerchantDTO merch = iBizMerchantInfoService.echoMerchantInfo(bizMerchantInfo);
        return AjaxResult.success(merch);
    }

    @ApiOperation("我的商户直连,posp")
    @PostMapping("/get/myMerch")
    public AjaxResult getMyMerch(@RequestBody MerchantDTO merchantDTO) {
        AjaxResult ajaxResult = AjaxResult.success();
        // 查询商户数量  直连
        int num = iBizMerchantEntryService.queryMyMerchNum(merchantDTO.getUserId());
        int numPOSP = iBizMerchantInfoService.queryMyMerchNum(merchantDTO.getUserId());

        List<PosOneMerchantInfo> list = iBizMerchantInfoService.getMyMerch(merchantDTO);
        ajaxResult.put("num", num+numPOSP);
        ajaxResult.put("data", list);
        return ajaxResult;
    }

    /**
     * 判断设备是否有押
     * @return
     */
    @PostMapping("/judgeCashPledge")
    public AjaxResult judgeCashPledge(@RequestBody BindPosDto bindPosDto){
        AjaxResult ajaxResult = AjaxResult.success();
        if (bindPosDto.getPosCode() == null || "".equals(bindPosDto.getPosCode())){
            return AjaxResult.error("设备不能为null");
        }
        BizPosMachine posMachineBySnCode = posMachineService.getPosMachineBySnCode(bindPosDto.getPosCode());
        //存储绑定的POSCODE到对应的商户中
        bizMerchantInfoMapper.savePosCodeByNo(bindPosDto.getMerchantNo(),posMachineBySnCode.getPosCode());
        if (posMachineBySnCode.getPosType().equals("6")){ //有押
            ajaxResult.put("type",1);
            return ajaxResult;
        }else { // 无押 调取绑定
            AjaxResult ajaxResult1 = bindingPosCode(bindPosDto);
            return ajaxResult1;
        }
    }

    /**
     * 判断图片视频是否上传
     * @param bindPosDto
     * @return
     */
    @PostMapping("/whetherPhotoVideo")
    public AjaxResult whetherPhotoVideo(@RequestBody BindPosDto bindPosDto){
        AjaxResult ajaxResult = AjaxResult.success();
        BizMerchantInfo bizMerchantInfo = bizMerchantInfoMapper.getLeShuaSn(bindPosDto.getMerchantNo());
        String type = "4";
        if (bizMerchantInfo.getWhetherPhoto().equals("0") && bizMerchantInfo.getWhetherVideo().equals("0")) {
            type = "1";  //图片视频没上传
        } else if (bizMerchantInfo.getWhetherVideo().equals("0") && bizMerchantInfo.getWhetherPhoto().equals("1")) {
            type = "2";  // 视频未上传
        } else if (bizMerchantInfo.getWhetherVideo().equals("1") && bizMerchantInfo.getWhetherPhoto().equals("0")) {
            type = "3";   // 图片未上传
        }
        ajaxResult.put("type",type);
        return ajaxResult;
    }


    @ApiOperation("posp绑定sn")
    @PostMapping("/binding/posCode")
    public AjaxResult bindingPosCode(@RequestBody BindPosDto bindPosDto) {
        if ("".equals(bindPosDto.getPosCode()) || bindPosDto.getPosCode() == null){
            return AjaxResult.error("请联系管理员");
        }
        AjaxResult ajaxResult = iBizMerchantInfoService.bindingPosCode(bindPosDto);
        return ajaxResult;
    }

    /**
     * 查询是否有记录
     */
    @PostMapping("/getMerchantInfoRecord")
    public AjaxResult getMerchantInfoRecord(@RequestBody BizMerchantInfo bizMerchantInfo) {
//        BizPosMachine bizPosMachine= posMachineService.getPosMachineBySnCode(bizMerchantInfo.getPosCode());
//        if(bizPosMachine==null){
//            return AjaxResult.success("当前设备不存在", 2);
//        }
//        if(null==bizMerchantInfo.getChannel()||"".equals(bizMerchantInfo.getChannel())){
//            return AjaxResult.success("渠道不能为空，请选择渠道", 2);
//        }
//        if(!bizPosMachine.getChannel().equals(bizMerchantInfo.getChannel())){
//            return AjaxResult.success("设备入库渠道与当前报件渠道不符", 2);
//        }
        List<BizMerchantInfo> bizMerchantInfo1 = iBizMerchantInfoService.getMerchantInfoRecord(bizMerchantInfo.getPosCode());
        if(bizMerchantInfo1.size() > 0){
            return AjaxResult.success("获取成功", 1);
        }else{
            return AjaxResult.success("获取成功", 0);
        }
    }


    /**
     * 机具解绑商户
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/pos/unbind")
    public AjaxResult unbindPos(@RequestBody BindPosDto bindPosDto) throws Exception {
        AjaxResult ajaxResult = iBizMerchantInfoService.unbindMerchant(bindPosDto);
        return ajaxResult;
    }
    /**
     * 机具转移
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/transfer")
    public AjaxResult transferPos(@RequestBody BizMerchantInfo bizMerchantInfo)  {
        int list = iBizMerchantInfoService.transferPos(bizMerchantInfo);
        return AjaxResult.success();
    }

    @ApiOperation("上送签名图片")
    @PostMapping("/photoUpload")
    public AjaxResult wishCheckPartnerPhotoUpload(@RequestBody BindPosDto bindPosDto) {
        AjaxResult ajaxResult = iBizMerchantInfoService.wishCheckPartnerPhotoUpload(bindPosDto);
        return ajaxResult;
    }

    @ApiOperation("上送视频")
    @PostMapping("/videoUpload")
    public AjaxResult wishCheckPartnerVideoUpload(@RequestBody BindPosDto bindPosDto) {
        AjaxResult ajaxResult = iBizMerchantInfoService.wishCheckPartnerVideoUpload(bindPosDto);
        return ajaxResult;
    }

    @GetMapping("/getArea")
    @ApiOperation("获得区域列表")
    public AjaxResult getChildrenByParentCode(CodeDto codeDto) {
        AjaxResult ajaxResult = AjaxResult.success();
        JSONObject params = new JSONObject();
        params.put("areaLevel", codeDto.getAreaLevel());// 层级 1-省 2-市 3 区/县
        params.put("parentCode", codeDto.getParentCode()); // 上级编码（层级areaLevel）
        System.out.println("处理前的请求参数：" + JSONObject.toJSONString(params));
        String resultResp = HttpUtil.doGetXXL(PosPCommonParamConfig.getGetArea(), params);
        System.out.println("返回值：" + resultResp);
        JSONObject jsonObject = JSONObject.parseObject(resultResp);
        if (jsonObject.getInteger("code") == 200) {
            Object data = jsonObject.get("data");
            ajaxResult.put("data", data);
        }
        // 把返回值转换成ResultDataModel类型
        //  ResultDataModel<AreaCode> resultDataModel = JSON.parseObject(resultResp, ResultDataModel.class);
        return ajaxResult;
    }

    @GetMapping("/banks")
    @ApiOperation("获得银行列表")
    public AjaxResult getBanks(BankDto bankDto) throws Exception {
        AjaxResult ajaxResult = AjaxResult.success();
        JSONObject params = new JSONObject();
        params.put("page", bankDto.getPage());
        params.put("pageSize", bankDto.getPageSize());
        params.put("bankName", bankDto.getBankName());
        System.out.println("处理前的请求参数：" + JSONObject.toJSONString(params));
        String resultResp = HttpUtil.doGetXXL(PosPCommonParamConfig.getBanks(), params);
        System.out.println("返回值：" + resultResp);
        JSONObject jsonObject = JSONObject.parseObject(resultResp);
        if (jsonObject.getInteger("code") == 200) {
            Object data = jsonObject.get("data");
            ajaxResult.put("data", data);
        }
        // 把返回值转换成ResultDataModel类型
        // ResultDataModel<T> resultDataModel = JSON.parseObject(resultResp, ResultDataModel.class);
        return ajaxResult;
    }

    @GetMapping("/branchs")
    @ApiOperation("获得银行支行列表")
    public Map<String, Object> getBranchs(BrankchDto brankchDto) throws Exception {
        AjaxResult ajaxResult = AjaxResult.success();
        JSONObject params = new JSONObject();
        params.put("page", brankchDto.getPage());
        params.put("pageSize", brankchDto.getPageSize());
        params.put("provinceCode", brankchDto.getProvinceCode());
        params.put("cityCode", brankchDto.getCityCode());
        params.put("bankCode", brankchDto.getBankCode());
        params.put("bankSiteName", brankchDto.getBankSiteName());
        String resultResp = HttpUtil.doGetXXL(PosPCommonParamConfig.getBranchs(), params);
        System.out.println("返回参数----》》》" + resultResp);
        JSONObject jsonObject = JSON.parseObject(resultResp);
        boolean code = jsonObject.containsKey("code");
        if (code) {
            return AjaxResult.error();
        } else {
            ajaxResult.put("data", jsonObject);
        }

        //  Map settleResult = JSON.toJavaObject(jsonObject, Map.class);
        return ajaxResult;
    }

    @ApiOperation("回显费率模板")
    @PostMapping("/echoFeeId")
    public AjaxResult echoFeeId() {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
//        String userFl=bizMerchantInfoMapper.getUserFl(sysUser.getUserId());
        AjaxResult ajaxResult = AjaxResult.success();
////        List<BizMercahntFeeNameDTO> list = iBizMerchantInfoService.echoFeeId();
//        List<BizMercahntFeeNameDTO> list = bizMerchantInfoMapper.getFeeId(userFl);
//        List<BizMercahntFeeNameDTO> reList=new ArrayList<BizMercahntFeeNameDTO>();
//        //判定费率显示例外
//        for(BizMercahntFeeNameDTO bizMercahntFeeNameDTO:list){
//            if(bizMercahntFeeNameDTO.getIsShow()!=null&&bizMercahntFeeNameDTO.getIsShow()==1){
//                if(StringUtils.isNotBlank(bizMercahntFeeNameDTO.getShowDepts())&& (!bizMercahntFeeNameDTO.getShowDepts().contains(sysUser.getDeptId()+","))){
//                    reList.add(bizMercahntFeeNameDTO);
//                }
//            }
//        }
//        list.removeAll(reList);
        List<BizMercahntFeeNameDTO> list = bizMerchantInfoMapper.getDefaultFeeId();// 0.63+3
        ajaxResult.put("data",list);
        return ajaxResult;
    }
    @ApiOperation("回显费率模板--跟据sn判断")
    @PostMapping("/echoFeeIdBySn")
    public AjaxResult echoFeeIdBySn(@RequestBody BizPosMachine bizPosMachine) {
        return iBizMerchantInfoService.echoFeeIdBySn(bizPosMachine);
    }



   /* @ApiOperation("获取商户审核状态")
    @PostMapping("/getMerchantStatus")
    public Map<String, Object> getMerchantStatus(@RequestBody BizMerchantInfo bizMerchantInfo) {
        JSONObject params = new JSONObject();
        params.put("merchantId", bizMerchantInfo.getMerchantId());
        String result = HttpUtil.doPostxxl(urlGetMerchantStatus, JSONObject.toJSONString(params));
        JSONObject jsonObject = JSON.parseObject(result);
        Map settleResult = JSON.toJavaObject(jsonObject, Map.class);
        return settleResult;
    }*/

    /**
     * 接收更新商户状态
     * @param bizMerchantInfo
     * @return
     */
    @PostMapping("/updateStatus")
    public AjaxResult updateStatus(@RequestBody BizMerchantInfo bizMerchantInfo) {
        System.out.println(bizMerchantInfo);
        BizMerchantInfo bizMerchantInfo1=iBizMerchantInfoService.getMerchantInfo(bizMerchantInfo);
        if(bizMerchantInfo1==null){
            System.out.println("系统不存在该商户！");
            return AjaxResult.success();
        }
        iBizMerchantInfoService.updateByMerchantCode(bizMerchantInfo);

        try {
            List<BizOrganization> list = bizMerchantService.selectBizOrganization("POSPBJ");
            if(list!=null&&list.size()>0){
                bizMerchantService.saveBackMerchant(bizMerchantInfo1.getMerchantCode());
            }else{
                return AjaxResult.success();
            }
            for (BizOrganization bizOrganization:list){
                if(bizMerchantInfo1.getMerchId().toString().equals(bizOrganization.getOrgncode())){
                    JSONObject params = new JSONObject();
                    params.put("uuid", bizMerchantInfo1.getUserName());
                    params.put("merchantCode", bizMerchantInfo1.getMerchantCode());
                    params.put("merchantId", bizMerchantInfo1.getMerchantId());
                    params.put("merchantKey", bizMerchantInfo1.getMerchantKey());
                    params.put("masterKeys", bizMerchantInfo1.getMasterKeys());
                    params.put("validationValue", bizMerchantInfo1.getValidationValue());
                    params.put("merchantLevel", bizMerchantInfo1.getMerchantLevel());
                    params.put("legalPersonName", bizMerchantInfo1.getLegalPersonName());
                    params.put("posCode", bizMerchantInfo1.getPosCode());
                    params.put("auditStatus", bizMerchantInfo.getAuditStatus());
                    params.put("merchantDesc", bizMerchantInfo.getMerchantDesc());
                    String url=bizOrganization.getOrgip()+bizOrganization.getOrgport();
                    System.out.println(JSONObject.toJSONString(params));
                    String result = HttpUtil.doPostxxl(url, JSONObject.toJSONString(params));
                    JSONObject jsonObject = JSON.parseObject(result);
                    if(jsonObject.getString("ret_code").equals("0")){
                        System.out.println("转发商户审核状态成功："+bizOrganization.getOrgnname()+"   "+bizMerchantInfo1.getMerchantCode());
                    }else{
                        System.out.println("转发商户审核状态失败："+bizOrganization.getOrgnname()+"   "+bizMerchantInfo1.getMerchantCode());
                    }
                }

            }
        }catch (Exception e ){
            e.printStackTrace();
        }

        return AjaxResult.success();
    }


    /**
     * 查询商户基本信息列表
     */
    @PreAuthorize("@ss.hasPermi('pos:merchantInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizMerchantInfo bizMerchantInfo) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser.getUserId() == 1){
            sysUser.setUserId(2L);
        }
        Long merchId = posMachineMapper.selectMerchId(sysUser.getUserId());
        bizMerchantInfo.setMerchId(merchId);
        startPage();
        List<BizMerchantInfo> list = iBizMerchantInfoService.queryList(bizMerchantInfo);
        for(BizMerchantInfo bizMerchantInfo1:list){
            if("1".equals(bizMerchantInfo1.getEnable())&&posMachineMapper.selectNoUser(sysUser.getUserId())!=0){
                bizMerchantInfo1.setFeeValue(bizMerchantInfo1.getNewFeeName());
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出商户基本信息列表
     */
    @PreAuthorize("@ss.hasPermi('pos:merchantInfo:export')")
    @Log(title = "商户基本信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(BizMerchantInfo bizMerchantInfo) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser.getUserId() == 1){
            sysUser.setUserId(2L);
        }
        Long merchId = posMachineMapper.selectMerchId(sysUser.getUserId());
        bizMerchantInfo.setMerchId(merchId);
        List<BizMerchantInfo> list = iBizMerchantInfoService.queryList(bizMerchantInfo);
        ExcelUtil<BizMerchantInfo> util = new ExcelUtil<BizMerchantInfo>(BizMerchantInfo.class);
        return util.exportExcel(list, "merchantInfo");
    }

    /**
     * 获取商户基本信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('pos:merchantInfo:query')")
    @GetMapping(value = "/{merchantCode}")
    public AjaxResult getInfo(@PathVariable("merchantCode") String merchantCode) {
        AjaxResult ajaxResult = AjaxResult.success();
        BizMerchantInfo bizMerchantInfo = new BizMerchantInfo();
        bizMerchantInfo.setMerchantCode(merchantCode);
        BizMerchantInfo byId = iBizMerchantInfoService.getMerchantInfo(bizMerchantInfo);
        ajaxResult.put("data",byId);
        return ajaxResult;
    }

    /**
     * 新增商户基本信息
     */
    @PreAuthorize("@ss.hasPermi('pos:merchantInfo:add')")
    @Log(title = "商户基本信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizMerchantInfo bizMerchantInfo) {
        return toAjax(iBizMerchantInfoService.save(bizMerchantInfo) ? 1 : 0);
    }

    /**
     * 修改商户基本信息
     */
    @PreAuthorize("@ss.hasPermi('pos:merchantInfo:edit')")
    @Log(title = "商户基本信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizMerchantInfo bizMerchantInfo) {
        return toAjax(iBizMerchantInfoService.updateById(bizMerchantInfo) ? 1 : 0);
    }

    /**
     * 删除商户基本信息
     */
    @PreAuthorize("@ss.hasPermi('pos:merchantInfo:remove')")
    @Log(title = "商户基本信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(iBizMerchantInfoService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    /**
     *  获取代理费率
     * @param bizMerchantInfo
     * @return
     */
    @PostMapping("/getAgentRate")
    public AjaxResult getAgentRate(@RequestBody BizMerchantInfo bizMerchantInfo) {
        String rate = iBizMerchantInfoService.getAgentRate(bizMerchantInfo.getPosCode());
        if(rate == null  || "".equals(rate)){
            return AjaxResult.error("获取失败");
        }
        return AjaxResult.success("获取成功", rate);
    }

    /**
     * 小程序获取登录账号信息
     * @param bizMerchantInfo
     * @return
     */
    @PostMapping("/getDeptIdByPosCode")
    public AjaxResult getDeptIdByPosCode(@RequestBody BizMerchantInfo bizMerchantInfo) {
        String deptId = iBizMerchantInfoService.getDeptIdByPosCode(bizMerchantInfo.getPosCode());
        return AjaxResult.success("获取成功", deptId);
    }

    /**
     * 查看是否报件成功
     */
    @PostMapping("/getMerchantInfoStatus")
    public AjaxResult getMerchantInfoStatus(@RequestBody BizMerchantInfo bizMerchantInfo) {
        String posCode = iBizMerchantInfoService.getMerchantInfoStatus(bizMerchantInfo.getPosCode());
        return AjaxResult.success("获取成功", posCode);
    }





    /**
     * 查询当前报件状态
     */
    @PostMapping("/backMerchantInfoStatus")
    public AjaxResult backMerchantInfoStatus(@RequestBody BizMerchantInfo bizMerchantInfo) {
        List<BizMerchantInfo> bizMerchantInfo1 = iBizMerchantInfoService.getMerchantInfoRecord(bizMerchantInfo.getPosCode());
        if(bizMerchantInfo1.size()>1){
            return AjaxResult.error("多个报件信息, 请联系服务商");
        }
        if(bizMerchantInfo1.size()==0){
            return AjaxResult.success("报件状态","0");
        }
        return AjaxResult.success("报件状态",bizMerchantInfo1.get(0).getAuditStatus());
    }

    @ApiOperation("小程序回显商户信息")
    @PostMapping("/backMerchantInfo")
    public AjaxResult backMerchantInfo(@RequestBody BizMerchantInfo bizMerchantInfo) {
        List<BizMerchantInfo> bizMerchantInfo1 = iBizMerchantInfoService.getMerchantInfoRecord(bizMerchantInfo.getPosCode());
        if(bizMerchantInfo1.size()>1){
            return AjaxResult.error("多个报件信息, 请联系服务商");
        }else{
            return AjaxResult.success(bizMerchantInfo1.get(0));
        }
    }

    /**
     * 验证身份证后6位
     */
    @PostMapping("/checkIdCardLastSix")
    public AjaxResult checkIdCardLastSix(@RequestBody BizMerchantInfo bizMerchantInfo) {
        BizMerchantInfo biz = iBizMerchantInfoService.getMerchantInfoBySn(bizMerchantInfo.getPosCode());
        if(biz.getCertificateNo().substring(12).equals(bizMerchantInfo.getIdCardLastSix())){
            return AjaxResult.success("验证成功");
        }else{
            return AjaxResult.error("验证失败");
        }

    }

    /**
     * 获取交易记录
     */
    @PostMapping("/transactionsData")
    public AjaxResult transactionsData(@RequestBody BizMerchantInfo bizMerchantInfo) {
        List<BizTransactionAmountEntityVO> bizMerchTransactions = iBizMerchTransactionsService.selectBizMerchTransactionsByCode(bizMerchantInfo);
        if(bizMerchTransactions != null && bizMerchTransactions.size()>0){
            return AjaxResult.success("获取成功",bizMerchTransactions);
        }else{
            return AjaxResult.success("暂无交易数据",new ArrayList<>());
        }

    }



    /**
     * 接收总平台推送的双录结果
     */
    @PostMapping("/updateWhetherStatus")
    public AjaxResult updateWhetherStatus(@RequestBody BizMerchantInfo bizMerchantInfo)  {
        BizMerchantInfo bizMerchantInfo1 = iBizMerchantInfoService.getMerchantInfoByMerchantId(bizMerchantInfo.getMerchantId());
        bizMerchantInfo1.setWhetherPhoto("1");
        bizMerchantInfo1.setWhetherVideo("1");
        if(iBizMerchantInfoService.saveOrUpdate(bizMerchantInfo1)){
            //核身成功直接绑定
            BindPosDto bindPosDto = new BindPosDto();
            bindPosDto.setMerchantNo(bizMerchantInfo1.getMerchantCode());
            bindPosDto.setPosCode(bizMerchantInfo1.getPosCode());
            AjaxResult ajaxResult = iBizMerchantInfoService.bindingPosCode(bindPosDto);
            if(ajaxResult.get("code").equals(200)){
                System.out.println(bizMerchantInfo1.getPosCode() +" 核身更新成功,绑定成功");
                return AjaxResult.success("核身更新成功,绑定成功");
            }else{
                System.out.println(bizMerchantInfo1.getPosCode() +" 核身更新成功,"+ajaxResult.get("msg"));
                return AjaxResult.success("核身更新成功,"+ajaxResult.get("msg"));
            }
        }else{
            System.out.println(bizMerchantInfo1.getPosCode() +" 核身更新失败");
            return AjaxResult.error("核身更新失败");
        }
    }

    /**
     * 获取省
     */
    @PostMapping("/add/merchant/GDBProvince")
    public AjaxResult GDBProvince() throws Exception {
        return iBizMerchantInfoService.GDBProvince();
    }

    /**
     * 获取市
     * @return
     * @throws Exception
     */
    @PostMapping("/add/merchant/GDBCity")
    public AjaxResult GDBCity(@RequestBody BizGdbArea bizGdbArea) throws Exception {
        return iBizMerchantInfoService.GDBCity(bizGdbArea);
    }

    /**
     * 获取区
     * @return
     * @throws Exception
     */
    @PostMapping("/add/merchant/GDBArea")
    public AjaxResult GDBArea(@RequestBody BizGdbArea bizGdbArea) throws Exception {
        return iBizMerchantInfoService.GDBArea(bizGdbArea);
    }

    /**
     * 广发卡绑卡
     */
    @PostMapping("/add/merchant/infoForGDB")
    public AjaxResult addMerchantsInfoForGDB(@RequestBody BizMerchantEpspBinding bizMerchantEpspBinding) throws Exception {
        return iBizMerchantInfoService.addMerchantsInfoForGDB(bizMerchantEpspBinding);
    }

    /**
     * 广发卡绑卡短息确认
     */
    @PostMapping("/add/merchant/smsCodeConfirm")
    public AjaxResult smsCodeConfirm(@RequestBody BizMerchantEpspBinding bizMerchantEpspBinding) throws Exception {
        return iBizMerchantInfoService.smsCodeConfirm(bizMerchantEpspBinding);
    }

    /**
     * 广发卡列表回显
     */
    @PostMapping("/backAccountList")
    public TableDataInfo backAccountList(@RequestBody BizMerchantEpspBinding bizMerchantEpspBinding) throws Exception {
        return getDataTable(iBizMerchantInfoService.backAccountList(bizMerchantEpspBinding));
    }

    /**
     * 开店宝新增商户基本信息
     *
     * @param bizMerchantInfo
     * @return
     */
    @PostMapping("/add/merchant/kdbinfo")
    public AjaxResult addMerchantsKDBInfo(@RequestBody BizMerchantInfo bizMerchantInfo) {
        System.out.println("商户报件："+bizMerchantInfo);
        AjaxResult ajaxResult = AjaxResult.success();
        try {
            String bankCode=this.getBankCode(bizMerchantInfo.getBankCardAccount());
            if(bankCode.equals("0")){
                ajaxResult.put("data", AjaxResult.error("银行卡号不符合，请重试。"));
                return ajaxResult;
            }
            bizMerchantInfo.setBankCode(bankCode);
        }catch (Exception e){
            e.printStackTrace();
            ajaxResult.put("data", AjaxResult.error("银行卡号不符合，请重试。"));
            return ajaxResult;
        }
        try {
            String provinceName = bizMerchantInfo.getProvinceName();
            if(provinceName == null || "".equals(provinceName)){
                ajaxResult.put("data", AjaxResult.error("未选择省"));
            }
            String cityName = bizMerchantInfo.getCityName();
            if(cityName == null || "".equals(cityName)){
                ajaxResult.put("data", AjaxResult.error("未选择市"));
            }
            String areaName = bizMerchantInfo.getAreaName();
            if(areaName == null || "".equals(areaName)){
                ajaxResult.put("data", AjaxResult.error("未选择区县"));
            }
            String bankName = getBankName(bizMerchantInfo.getBankCardAccount());
            if(bankName == "FAILURE"){
                ajaxResult.put("data", AjaxResult.error("银行卡号不符合，请重试。"));
            }
            logger.info(bizMerchantInfo.getBankCardAccount(),"*-*-*-*provinceName:"+provinceName,"cityName:"+cityName,"areaName"+areaName);
            //详细查区县
            BizKdbBank bizKdbBank = bizMerchantInfoMapper.getKdbBank(provinceName,cityName,areaName,bankName);
            if(bizKdbBank != null){
                bizMerchantInfo.setUnionpayCode(bizKdbBank.getCode());
                bizMerchantInfo.setBankSite(bizKdbBank.getName());
            }else{// 查市
                bizKdbBank = bizMerchantInfoMapper.getKdbBankEndCity(provinceName,cityName,bankName);
                if(bizKdbBank != null){
                    bizMerchantInfo.setUnionpayCode(bizKdbBank.getCode());
                    bizMerchantInfo.setBankSite(bizKdbBank.getName());
                }else{// 查省
                    bizKdbBank = bizMerchantInfoMapper.getKdbBankEndProvince(provinceName,bankName);
                    if(bizKdbBank != null){
                        bizMerchantInfo.setUnionpayCode(bizKdbBank.getCode());
                        bizMerchantInfo.setBankSite(bizKdbBank.getName());
                    }else{
                        ajaxResult.put("data", AjaxResult.error("不支持改地区银行，请更换结算卡"));
                    }
                }
            }
            logger.info(bizMerchantInfo.getUnionpayCode(),bizMerchantInfo.getBankSite());

//                String unionpayCode=this.getUnionpayCode(bizMerchantInfo);
//                if(unionpayCode.equals("0")){
//                    ajaxResult.put("data", AjaxResult.error("不支持改地区银行，请更换结算卡"));
//                    return ajaxResult;
//                }
//                if(unionpayCode.indexOf(",")>0){
//                    String [] ucs=unionpayCode.split(",");
//                    bizMerchantInfo.setUnionpayCode(ucs[0]);
//                    bizMerchantInfo.setBankSite(ucs[1]);
//                }else{
//                    bizMerchantInfo.setUnionpayCode(unionpayCode);
//                }


        }catch (Exception e){
            e.printStackTrace();
            ajaxResult.put("data", AjaxResult.error("联行号获取失败，请重试。"));
            return ajaxResult;
        }
        if(null!=bizMerchantInfo.getContactPhoneNo()){
            bizMerchantInfo.setContactPhoneNo(bizMerchantInfo.getContactPhoneNo().replace(" ",""));
            bizMerchantInfo.setPhone(bizMerchantInfo.getPhone().replace(" ",""));
            bizMerchantInfo.setBankCardPhone(bizMerchantInfo.getBankCardPhone().replace(" ",""));
            bizMerchantInfo.setClientServicePhoneNo(bizMerchantInfo.getClientServicePhoneNo().replace(" ",""));
            if(bizMerchantInfo.getContactPhoneNo().length()!=11){
                ajaxResult.put("data", AjaxResult.error("手机号长度不正确，请重新输入手机号"));
                return ajaxResult;
            }
        }else{
            ajaxResult.put("data", AjaxResult.error("手机号不能为空，请填写手机号"));
            return ajaxResult;
        }
        if(null!=bizMerchantInfo.getCertificateNo()){
            bizMerchantInfo.setCertificateNo(bizMerchantInfo.getCertificateNo().replace(" ",""));
        }
        if(null!=bizMerchantInfo.getBankCardAccount()){
            bizMerchantInfo.setBankCardAccount(bizMerchantInfo.getBankCardAccount().replace(" ",""));
        }
        if(null==bizMerchantInfo.getActiveLatitude()||"".equals(bizMerchantInfo.getActiveLatitude())){
            ajaxResult.put("data", AjaxResult.error("经纬度不能为空，请检查手机定位是否开启！"));
            return ajaxResult;
        }
        if(null==bizMerchantInfo.getActiveLongitude()||"".equals(bizMerchantInfo.getActiveLongitude())){
            ajaxResult.put("data", AjaxResult.error("经纬度不能为空，请检查手机定位是否开启！"));
            return ajaxResult;
        }
//        if(null==bizMerchantInfo.getRegisterLatitude()||"".equals(bizMerchantInfo.getRegisterLatitude())){
//            ajaxResult.put("data", AjaxResult.error("经纬度不能为空，请检查手机定位是否开启！"));
//            return ajaxResult;
//        }
//        if(null==bizMerchantInfo.getRegisterLongitude()||"".equals(bizMerchantInfo.getRegisterLongitude())){
//            ajaxResult.put("data", AjaxResult.error("经纬度不能为空，请检查手机定位是否开启！"));
//            return ajaxResult;
//        }
        bizMerchantInfo.setPosCode(bizMerchantInfo.getPosCode().replace(" ",""));
        bizMerchantInfo.setPosCode(bizMerchantInfo.getPosCode().toUpperCase());
        JSONObject result = iBizMerchantInfoService.addMerchantsKDBInfo(bizMerchantInfo);
        ajaxResult.put("data", result);
        return ajaxResult;
    }
    /**
     * 开店宝新增商户回调
     *
     * @param bizMerchantInfo
     * @return
     */
    @PostMapping("/add/merchant/kdbCallback")
    public AjaxResult kdbCallback(@RequestBody BizMerchantInfo bizMerchantInfo) {
        AjaxResult ajaxResult = AjaxResult.success();
        JSONObject result = iBizMerchantInfoService.kdbCallback(bizMerchantInfo);
        ajaxResult.put("data", result);
        return ajaxResult;
    }
    /**
     * 开店宝绑定状态推送接口
     *
     * @param bizMerchantInfo
     * @return
     */
    @PostMapping("/add/merchant/kdbBindCallback")
    public AjaxResult kdbBindCallback(@RequestBody BizMerchantInfo bizMerchantInfo) {
        AjaxResult ajaxResult = AjaxResult.success();
        JSONObject result = iBizMerchantInfoService.kdbBindCallback(bizMerchantInfo);
        ajaxResult.put("data", result);
        return ajaxResult;
    }


    public String getBankName(String bankCardAccount) throws Exception {
        JSONObject cardNo=new JSONObject();
        cardNo.put("cardNo",bankCardAccount);
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getObtainBank(), JSONObject.toJSONString(cardNo));
        if(StringUtil.isNotEmpty(result)){
            JSONObject jsonResult=JSONObject.parseObject(result);
            if("200".equals(jsonResult.getString("code"))){
                return jsonResult.getString("data");// 银行名称
            }
        }
        return "FAILURE";
    }
    @PostMapping("/getBankCode")
    public String getBankCode(String bankCardAccount) throws Exception {
        JSONObject cardNo=new JSONObject();
        cardNo.put("cardNo",bankCardAccount);
        String result = HttpUtil.doPostxxl(PosPCommonParamConfig.getObtainBank(), JSONObject.toJSONString(cardNo));
        BankDto bankDto=new BankDto();
        if(StringUtil.isNotEmpty(result)){
            JSONObject jsonResult=JSONObject.parseObject(result);
            if("200".equals(jsonResult.getString("code"))){
                bankDto.setBankName(jsonResult.getString("data"));
            }else{
                return "0";
            }
        }else{
            return "0";
        }
        bankDto.setPage("1");
        bankDto.setPageSize("1");
        AjaxResult ajaxResult=this.getBanks(bankDto);
        JSONObject jsonObject = JSONObject.parseObject(ajaxResult.get("data").toString());
        JSONArray jsonArray=jsonObject.getJSONArray("list");
        JSONObject jsonObject1=new JSONObject();
        if(jsonArray.size()>0){
            jsonObject1=jsonArray.getJSONObject(0);
            String bankCode=jsonObject1.getString("code");
            return bankCode;
        }
        return "0";
    }
    @PostMapping("/getUnionpayCode")
    public String getUnionpayCode(@RequestBody BizMerchantInfo bizMerchantInfo) throws Exception {
        BrankchDto brankchDto=new BrankchDto();
        brankchDto.setPage("1");
        brankchDto.setPageSize("1");
        brankchDto.setProvinceCode(bizMerchantInfo.getBankProvince());
        brankchDto.setCityCode(bizMerchantInfo.getBankCity());
        brankchDto.setBankCode(bizMerchantInfo.getBankCode());
        Map<String, Object> ajaxResult=this.getBranchs(brankchDto);
        JSONObject jsonObject = JSONObject.parseObject(ajaxResult.get("data").toString());
        JSONArray jsonArray=jsonObject.getJSONArray("list");
        JSONObject jsonObject1=new JSONObject();
        if(jsonArray.size()>0){
            jsonObject1=jsonArray.getJSONObject(0);
            String unionpayCode=jsonObject1.getString("code");
            unionpayCode+=","+jsonObject1.getString("name");
            return unionpayCode;
        }else{
            brankchDto.setCityCode(null);
            Map<String, Object> ajaxResult1=this.getBranchs(brankchDto);
            JSONObject jsonObject11 = JSONObject.parseObject(ajaxResult1.get("data").toString());
            JSONArray jsonArray1=jsonObject11.getJSONArray("list");
            JSONObject jsonObject2=new JSONObject();
            if(jsonArray.size()>0){
                jsonObject2=jsonArray.getJSONObject(0);
                String unionpayCode=jsonObject2.getString("code");
                unionpayCode+=","+jsonObject1.getString("name");
                return unionpayCode;
            }
        }
        return "0";
    }
    /**
     * 新增商户基本信息
     *
     * @param bizMerchantInfo
     * @return
     */
    @PostMapping("/add/merchant/online")
    public AjaxResult addMerchantsOnline(@RequestBody BizMerchantInfo bizMerchantInfo) {
        System.out.println("商户报件："+bizMerchantInfo);
        AjaxResult ajaxResult = AjaxResult.success();
        try {
            String bankCode=this.getBankCode(bizMerchantInfo.getBankCardAccount());
            if(bankCode.equals("0")){
                ajaxResult.put("data", AjaxResult.error("银行卡号不符合，请重试。"));
                return ajaxResult;
            }
            bizMerchantInfo.setBankCode(bankCode);
        }catch (Exception e){
            e.printStackTrace();
            ajaxResult.put("data", AjaxResult.error("银行卡号不符合，请重试。"));
            return ajaxResult;
        }
        try {
            String unionpayCode=this.getUnionpayCode(bizMerchantInfo);
            if(unionpayCode.equals("0")){
                ajaxResult.put("data", AjaxResult.error("不支持改地区银行，请更换结算卡"));
                return ajaxResult;
            }
            if(unionpayCode.indexOf(",")>0){
                String [] ucs=unionpayCode.split(",");
                bizMerchantInfo.setUnionpayCode(ucs[0]);
                bizMerchantInfo.setBankSite(ucs[1]);
            }else{
                bizMerchantInfo.setUnionpayCode(unionpayCode);
            }

        }catch (Exception e){
            e.printStackTrace();
            ajaxResult.put("data", AjaxResult.error("联行号获取失败，请重试。"));
            return ajaxResult;
        }
        if(null!=bizMerchantInfo.getContactPhoneNo()){
            bizMerchantInfo.setContactPhoneNo(bizMerchantInfo.getContactPhoneNo().replace(" ",""));
            bizMerchantInfo.setPhone(bizMerchantInfo.getPhone().replace(" ",""));
            bizMerchantInfo.setBankCardPhone(bizMerchantInfo.getBankCardPhone().replace(" ",""));
            bizMerchantInfo.setClientServicePhoneNo(bizMerchantInfo.getClientServicePhoneNo().replace(" ",""));
            if(bizMerchantInfo.getContactPhoneNo().length()!=11){
                ajaxResult.put("data", AjaxResult.error("手机号长度不正确，请重新输入手机号"));
                return ajaxResult;
            }
        }else{
            ajaxResult.put("data", AjaxResult.error("手机号不能为空，请填写手机号"));
            return ajaxResult;
        }
        if(null!=bizMerchantInfo.getCertificateNo()){
            bizMerchantInfo.setCertificateNo(bizMerchantInfo.getCertificateNo().replace(" ",""));
        }
        if(null!=bizMerchantInfo.getBankCardAccount()){
            bizMerchantInfo.setBankCardAccount(bizMerchantInfo.getBankCardAccount().replace(" ",""));
        }
        if(null==bizMerchantInfo.getActiveLatitude()||"".equals(bizMerchantInfo.getActiveLatitude())){
            ajaxResult.put("data", AjaxResult.error("经纬度不能为空，请检查手机定位是否开启！"));
            return ajaxResult;
        }
        if(null==bizMerchantInfo.getActiveLongitude()||"".equals(bizMerchantInfo.getActiveLongitude())){
            ajaxResult.put("data", AjaxResult.error("经纬度不能为空，请检查手机定位是否开启！"));
            return ajaxResult;
        }
//        if(null==bizMerchantInfo.getRegisterLatitude()||"".equals(bizMerchantInfo.getRegisterLatitude())){
//            return AjaxResult.error("经纬度不能为空，请检查手机定位是否开启！");
//        }
//        if(null==bizMerchantInfo.getRegisterLongitude()||"".equals(bizMerchantInfo.getRegisterLongitude())){
//            return AjaxResult.error("经纬度不能为空，请检查手机定位是否开启！");
//        }
        AjaxResult ajaxResult1 = iBizMerchantInfoService.addMerchantsOnline(bizMerchantInfo);
        ajaxResult.put("data", ajaxResult1);
        return ajaxResult;
    }
    /**
     * 线上pos费率列表
     * @return
     */
    @PostMapping("/echoFeeIdOnline")
    public AjaxResult echoFeeIdOnline() {
        AjaxResult ajaxResult = AjaxResult.success();
        List<BizMercahntFeeNameDTO> list = iBizMerchantInfoService.echoFeeIdOnline();
        ajaxResult.put("data",list);
        return ajaxResult;
    }
    /**
     * 线上pos激活接口
     *
     * @param bizMerchantInfo
     * @return
     */
    @PostMapping("/activeStatus")
    public AjaxResult onlineBinding(@RequestBody BizMerchantInfo bizMerchantInfo) {
        AjaxResult ajaxResult = AjaxResult.success();
        System.out.println("线上pos激活接口，商户号："+bizMerchantInfo.getMerchantCode()+"激活标识："+bizMerchantInfo.getActiveStatus());
        JSONObject result = iBizMerchantInfoService.onlineBinding(bizMerchantInfo);
        ajaxResult.put("data", result);
        return ajaxResult;
    }
    /**
     * 线上pos修改结算卡
     * @param bizMerchantInfo
     * @return
     */
    @PostMapping("/updateSettleAccountOnline")
    public AjaxResult updateSettleAccountOnline(@RequestBody BizMerchantInfo bizMerchantInfo) {
        AjaxResult ajaxResult = AjaxResult.success();
        JSONObject result = iBizMerchantInfoService.updateSettleAccountOnline(bizMerchantInfo);
        ajaxResult.put("data", result);
        return ajaxResult;

    }
    /**
     * 新增商户基本信息
     *
     * @param bizMerchantInfo
     * @return
     */
    @PostMapping("/add/merchant/qbInfo")
    public AjaxResult addMerchantsQBInfo(@RequestBody BizMerchantInfo bizMerchantInfo) {
        System.out.println("商户报件：" + bizMerchantInfo);
        AjaxResult ajaxResult = AjaxResult.success();
        try {
            String bankCode = this.getBankCode(bizMerchantInfo.getBankCardAccount());
            if (bankCode.equals("0")) {
                ajaxResult.put("data", AjaxResult.error("银行卡号不符合，请重试。"));
                return ajaxResult;
            }
            bizMerchantInfo.setBankCode(bankCode);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("data", AjaxResult.error("银行卡号不符合，请重试。"));
            return ajaxResult;
        }
        try {
            String unionpayCode = this.getUnionpayCode(bizMerchantInfo);
            if (unionpayCode.equals("0")) {
                ajaxResult.put("data", AjaxResult.error("不支持改地区银行，请更换结算卡"));
                return ajaxResult;
            }
            if (unionpayCode.indexOf(",") > 0) {
                String[] ucs = unionpayCode.split(",");
                bizMerchantInfo.setUnionpayCode(ucs[0]);
                bizMerchantInfo.setBankSite(ucs[1]);
            } else {
                bizMerchantInfo.setUnionpayCode(unionpayCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("data", AjaxResult.error("联行号获取失败，请重试。"));
            return ajaxResult;
        }
        if (null != bizMerchantInfo.getContactPhoneNo()) {
            bizMerchantInfo.setContactPhoneNo(bizMerchantInfo.getContactPhoneNo().replace(" ", ""));
            bizMerchantInfo.setPhone(bizMerchantInfo.getPhone().replace(" ", ""));
            bizMerchantInfo.setBankCardPhone(bizMerchantInfo.getBankCardPhone().replace(" ", ""));
            bizMerchantInfo.setClientServicePhoneNo(bizMerchantInfo.getClientServicePhoneNo().replace(" ", ""));
            if (bizMerchantInfo.getContactPhoneNo().length() != 11) {
                ajaxResult.put("data", AjaxResult.error("手机号长度不正确，请重新输入手机号"));
                return ajaxResult;
            }
        } else {
            ajaxResult.put("data", AjaxResult.error("手机号不能为空，请填写手机号"));
            return ajaxResult;
        }
        if (null != bizMerchantInfo.getCertificateNo()) {
            bizMerchantInfo.setCertificateNo(bizMerchantInfo.getCertificateNo().replace(" ", ""));
        }
        if (null != bizMerchantInfo.getBankCardAccount()) {
            bizMerchantInfo.setBankCardAccount(bizMerchantInfo.getBankCardAccount().replace(" ", ""));
        }
        if (null == bizMerchantInfo.getActiveLatitude() || "".equals(bizMerchantInfo.getActiveLatitude())) {
            ajaxResult.put("data", AjaxResult.error("经纬度不能为空，请检查手机定位是否开启！"));
            return ajaxResult;
        }
        if (null == bizMerchantInfo.getActiveLongitude() || "".equals(bizMerchantInfo.getActiveLongitude())) {
            ajaxResult.put("data", AjaxResult.error("经纬度不能为空，请检查手机定位是否开启！"));
            return ajaxResult;
        }
//        if(null==bizMerchantInfo.getRegisterLatitude()||"".equals(bizMerchantInfo.getRegisterLatitude())){
//            return AjaxResult.error("经纬度不能为空，请检查手机定位是否开启！");
//        }
//        if(null==bizMerchantInfo.getRegisterLongitude()||"".equals(bizMerchantInfo.getRegisterLongitude())){
//            return AjaxResult.error("经纬度不能为空，请检查手机定位是否开启！");
//        }
        bizMerchantInfo.setPosCode(bizMerchantInfo.getPosCode().replace(" ", ""));
        bizMerchantInfo.setPosCode(bizMerchantInfo.getPosCode().toUpperCase());
        AjaxResult ajaxResult1 = iBizMerchantInfoService.addMerchantsQbInfo(bizMerchantInfo);
        ajaxResult.put("data", ajaxResult1);
        return ajaxResult;
    }
    /**
     * 获取下拉列表数据--目前开店宝使用--20240116
     * @return
     */
    @PostMapping("/getSelectData")
    public AjaxResult getSelectData(){
        AjaxResult ajaxResult=AjaxResult.success();
        ajaxResult.put("busNatureList",sysDictDataMapper.selectDictDataByType("bus_nature_type"));//1:个体 2:企业 3：小微（门头照和场景照必填）
        ajaxResult.put("legalpersonIsSettList",sysDictDataMapper.selectDictDataByType("legalperson_is_sett"));//N 法人  Y 非法人结算
        ajaxResult.put("settAccMark",sysDictDataMapper.selectDictDataByType("sett_acc_mark"));//0对公1对私
        ajaxResult.put("mercTypeMCC",bizMerchantInfoMapper.kdbIndustry());//0对公1对私
        return ajaxResult;
    }
    /**
     * 获取下拉列表数据--目前乐刷使用
     * @return
     */
    @PostMapping("/getLSData")
    public AjaxResult getLSData(){
        AjaxResult ajaxResult=AjaxResult.success("请求成功");
        ajaxResult.put("lsMCC",bizMerchantInfoMapper.lsIndustry());
        return ajaxResult;
    }
    @PostMapping("/getIndustry")
    public AjaxResult getIndustry(){
        AjaxResult ajaxResult=AjaxResult.success();
        ajaxResult.put("data",iBizMerchantEntryService.getIndustry());
        return ajaxResult;
    }
    /**
     * 开店宝小微商户5上限查询接口
     * @return
     */
    @PostMapping("/queryKDBUpper")
    public AjaxResult queryKDBUpper(@RequestBody BizMerchantInfo bizMerchantInfo){
        return iBizMerchantInfoService.queryKDBUpper(bizMerchantInfo);
    }


    /**
     * 查询可选商户名头
     */
    @PostMapping("/cupsNameList")
    public AjaxResult cupsNameList(@RequestBody String json){
        Map<String,String> map = HttpUtil.generateMap(json);
        String idCard = map.get("idCard");
        List<BizMerchantInfo> cupsNameList = iBizMerchantInfoService.getCupsNameList(idCard);
        if(cupsNameList.size() > 0){
            return AjaxResult.success("",cupsNameList);
        }else{
            return AjaxResult.error("未查询到数据");
        }
    }

    /**
     * 当前身份证的全部成功报件信息
     */
    @PostMapping("/info/for/applet")
    public AjaxResult infoForApplet(@RequestBody String json) {
        Map<String, String> map = HttpUtil.generateMap(json);
        String idCard = map.get("idCard");
        List<BizMerchantInfo> cupsNameList = iBizMerchantInfoService.getMerchantInfoList(idCard);
        if(cupsNameList.size() > 0){
            return AjaxResult.success("",cupsNameList);
        }else{
            return AjaxResult.error("未查询到数据");
        }
    }

    /**
     * 切换名头   也就是从这个商户上换绑到另一商户上
     * @param json
     * @return
     */
    @PostMapping("/changeCupsName")
    public AjaxResult changeCupsName(@RequestBody String json){
        return AjaxResult.error("功能维护中,请关注后续通知");
//        return iBizMerchantInfoService.changeCupsName(json);
    }


    /**
     * 企业后台进件
     * @param json
     * @return
     */
    @PostMapping("/excuteSubmitNewQyMerchant")
    public AjaxResult excuteSubmitNewMerchant(@RequestBody String json){
        return iBizMerchantInfoService.excuteSubmitNewMerchant(json);
    }

    /**
     * 小微后台进件
     * @param json
     * @return
     */
    @PostMapping("/excuteSubmitNewXwMerchant")
    public AjaxResult excuteSubmitNewXwMerchant(@RequestBody String json){
        return iBizMerchantInfoService.excuteSubmitNewXwMerchant(json);
    }

    /**
     * 无sn进件信息
     */
    @PostMapping("/noSnMerchantInfo")
    public AjaxResult noSnMerchantInfo(@RequestBody String json){
        return iBizMerchantInfoService.noSnMerchantInfo(json);
    }


    /**
     * 更新为开店宝商户号
     */
    @PostMapping("/changeKdbMerchantId")
    public AjaxResult changeKdbMerchantId(@RequestBody String json){
        return iBizMerchantInfoService.changeKdbMerchantId(json);
    }


    @PostMapping("/bffr")
    public AjaxResult bffr() throws ParseException {
        return iBizMerchantInfoService.bffr();
    }


    @PostMapping("/update/rate")
    public AjaxResult updateRate(){
        return iBizMerchantInfoService.updateRate();
    }



    /**
     * 接收乐汇审核信息
     */
    @PostMapping("/receiveLHExamine")
    public AjaxResult receiveLHExamine(@RequestBody JSONObject json) {
        return iBizMerchantInfoService.receiveLHExamine(json);
    }

    @PostMapping("/tttt")
    public AjaxResult ttt(){
        return iBizMerchantInfoService.tttt();
    }


    @PostMapping("/updateFee")
    public AjaxResult updateFee(){
        return iBizMerchantInfoService.updateFee();
    }



    @ApiOperation("商户列表")
    @PostMapping("/app/back/merchantInfo/list")
    public JSONObject appBackMerchantInfoList(@RequestBody BizMerchantInfo bizMerchantInfo){
        return iBizMerchantInfoService.appBackMerchantInfoList(bizMerchantInfo);
    }


    @ApiOperation("商户详情")
    @PostMapping("/app/back/merchantInfo/detail")
    public AjaxResult appBackMerchantInfoDetail(@RequestBody BizMerchantInfo bizMerchantInfo) throws ParseException {
        return iBizMerchantInfoService.appBackMerchantInfoDetail(bizMerchantInfo);
    }


    @ApiOperation("代理列表")
    @PostMapping("/app/back/partner/list")
    public AjaxResult appBackPartnerList(@RequestBody BizMerchant bizMerchant){
        return iBizMerchantInfoService.appBackPartnerList(bizMerchant);
    }


    @ApiOperation("嘉联商户绑定通知")
    @PostMapping("/JL/merchant/info/notice")
    public JSONObject jlMerchantInfoNotice(@RequestBody BizJLMerchantInfo bizJLMerchantInfo){
        return iBizMerchantInfoService.jlMerchantInfoNotice(bizJLMerchantInfo);
    }



    @PostMapping("/sendSms/test")
    public void sendSmsTest(){
        String url = "https://api-v4.mysubmail.com/sms/send.json";
        String content = "【短信通知】您的短信验证码为588008";
        String appid = "109739";
        String to = "16643588008";
        String signature = "fd19bab0745052d3d9fd4de0910808d9";
        JSONObject map = new JSONObject();
        map.put("appid",appid);
        map.put("content",content);
        map.put("to",to);
        map.put("signature",signature);
        System.out.println("地址"+url);
        System.out.println("参数"+map.toString());
        String result = PublicUtil.sendSms(url,map);

    }


    @ApiOperation("沉默商户")
    @PostMapping("/silent/merchantInfo")
    public AjaxResult slientMerchantInfo(@RequestBody BizMerchantInfo bizMerchantInfo){
        return iBizMerchantInfoService.slientMerchantInfo(bizMerchantInfo);
    }

    @ApiOperation("未激活商户")
    @PostMapping("/unActive/merchantInfo")
    public AjaxResult unActiveMerchantInfo(@RequestBody BizMerchantInfo bizMerchantInfo){
        return iBizMerchantInfoService.unActiveMerchantInfo(bizMerchantInfo);
    }

    @ApiOperation("伪激活商户")
    @PostMapping("/failureActive/merchantInfo")
    public AjaxResult failureActiveMerchantInfo(@RequestBody BizMerchantInfo bizMerchantInfo){
        return iBizMerchantInfoService.failureActiveMerchantInfo(bizMerchantInfo);
    }


    @PostMapping("/executeQueryTrans")
    public TableDataInfo executeQueryTrans(@RequestBody BizMerchantInfo bizMerchantInfo){
        startPage();
        return getDataTable(iBizMerchantInfoService.executeQueryTrans(bizMerchantInfo));
    }


    @PostMapping("/executeHandleEdit")
    public AjaxResult executeHandleEdit(@RequestBody AllocationRelation allocationRelation){
        return iAllocationRelationService.executeHandleEdit(allocationRelation);
    }

}
